package com.home.fansea.fliter;

import com.home.fansea.config.ImgProtectConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @Projectname: MiniXYIot
 * @Filename: PictureFilter
 * @Author: FANSEA
 * @Data:2024/5/20 21:41
 */
@Component
public class PictureFilter implements HandlerInterceptor {
    // 防盗链配置
    @Autowired
    private ImgProtectConfig imgProtectConfig;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!imgProtectConfig.isEnable()) {
            return true;
        }
        if (request.getRequestURI().endsWith(".png")||request.getRequestURI().endsWith(".jpg")||request.getRequestURI().endsWith(".jpeg")||request.getRequestURI().endsWith(".gif")){
            String referer = request.getHeader("Referer");
            if (referer == null || imgProtectConfig.isAllowBrowser()) {
                return true;
            }else if (referer !=null && isAllowDomain(referer)){
                return true;
            }else {
                response.setStatus(403);
                return false;
            }
        }
        return true;
    }

    private boolean isAllowDomain(String referer)  {
        String allowedReferer = imgProtectConfig.getAllowedReferer();
        if (allowedReferer.trim() !=null && !allowedReferer.trim().isEmpty()) {
            Set<String> allowDomains = new HashSet<>(Arrays.asList(allowedReferer.split(",")));
            return allowDomains.contains(referer);
        }
        return false;
    }
}
